import { toRaw } from 'vue'
import type { PiniaPluginContext } from 'pinia'

function setStorage(key:string,value:any){
localStorage.setItem(key,JSON.stringify(value))
}

function getStorage(key:string){
  return localStorage.getItem(key)?JSON.parse(localStorage.getItem(key) as string):''
}

//函数柯里化
 const PersistenceStore=(options:{key:string})=>{
  return (context:PiniaPluginContext)=>{
    const {store} =context
    const data=getStorage(options.key)
    store.$subscribe(()=>{
      setStorage(options.key,toRaw(store.$state))
    })
    return {...data}
  }
}

export default PersistenceStore
